package org.example;

import org.junit.jupiter.api.Test;
import org.openjdk.jol.info.ClassLayout;

/**
 * @Email: jixiaotian.ch@foxmail.com
 * @Date : 2020/9/23 14:57
 */
public class LockDemo {

    /*
    锁的升级过程
    0 01 无锁
    0 00 轻量级锁
    0 10 重量级锁
    0 11 GC锁
    1 01 偏向锁
     */
    public static void main(String[] args) throws InterruptedException {
        LockDemo lockDemo = new LockDemo();
        //打开偏向锁后，t1此时抢占锁时无线程竞争，所以是偏向锁
        Thread t1 = new Thread(()->{
            synchronized (lockDemo) {
                System.out.println("t1抢占到锁");
                System.out.println(ClassLayout.parseInstance(lockDemo).toPrintable());
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //t2抢占锁的时候t1并没有释放，所以t2无法抢占到偏向锁，升级为000轻量级锁
                new Thread(()->{
                    synchronized (lockDemo) {
                        System.out.println("t2抢占到锁");
                        System.out.println(ClassLayout.parseInstance(lockDemo).toPrintable());
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //t3抢占锁的时候t1、t2都没有释放，所以t3无法抢占到偏向锁也无法抢到轻量级锁，因此t3升级为010重量级锁
                        new Thread(()->{
                            synchronized (lockDemo) {
                                System.out.println("t3抢占到锁");
                                System.out.println(ClassLayout.parseInstance(lockDemo).toPrintable());
                            }
                        }).start();

                    }
                }).start();

            }
        });
        t1.start();

    }


    @Test
    public void lockUpgradeTest() throws InterruptedException {
        LockDemo lockDemo = new LockDemo();
        Thread t1 = new Thread(()->{
            synchronized (lockDemo) {
                System.out.println("t1抢占到锁");
                System.out.println(ClassLayout.parseInstance(lockDemo).toPrintable());
            }
        });
        t1.start();
//        synchronized (lockDemo) {
//            System.out.println("Main抢占到锁");
//            System.out.println(ClassLayout.parseInstance(lockDemo).toPrintable());
//        }


    }
}
